<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2019/11/28
 * Time: 15:27
 */

namespace app\adminapiv3\service;


use app\common\model\RivestCipher;
use app\common\service\ServerProxy;
use app\common\service\VirtualPoxyIp;
use MongoDB\Driver\Server;

class Install extends Base
{

    /**
     * @name 在线授权
     * @param $authRes
     * @author wx
     * @date 2020/6/9 13:30
     */
    function online($authRes)
    {
        $authServer = new ServerAuth();

        $authData = $authRes['data'];
        foreach ($authData as $k => $v){
            $authServer->checkData($v);
            $authServer->checkLocal($v);
            $nowTime = $v['stime'] > time() ? $v['stime'] : time();

            //检测授权时间
            $authServer->checkAuthTime($v, $nowTime);

        }

        //写进授权临时文件
        file_put_contents('./Install/auth.json', json_encode($authData));
    }

    /**
     * @name 离线授权
     * @param $file
     * @author wx
     * @date 2019/11/29 10:18
     */
    function offline($file)
    {
        //1. 上传文件
        $uploadServer = new Upload();
        $uploadAuthDir = '../runtime/Upload/Auth';
        $uploadRes = $uploadServer->upload($file, $uploadAuthDir,'key',5*1024*1024);

        if($uploadRes['code'] != 0){
            returnErrJson($this->CODE_FAIL, $uploadRes['msg']);
        }




        //2. 解密文件
        $authFile = $uploadRes['path'].$uploadRes['file_name'];
        $rc4Server = new RivestCipher();
        $authServer = new ServerAuth();

        $content = file_get_contents($authFile);
        $authInfo = $rc4Server->decrypt($content);

        if(!$authInfo){
            $this->setError($this->CODE_FAIL, '错误的授权文件');
            return false;
        }


        foreach ($authInfo as $k => $v){
            $authServer->checkData($v);
            $authServer->checkLocal($v);
            //检测授权时间
            $nowTime = $v['stime'] > time() ? $v['stime'] : time();
            $authServer->checkAuthTime($v, $nowTime);

        }

        //4. 将授权信息组装成一条信息放在临时授权文件中
        $authData['stime'] = $nowTime;
        file_put_contents('./Install/auth.json',json_encode($authInfo));
        file_put_contents('./Install/system_time.json', json_encode($authData));

        //5. over
        return true;
    }


    /**
     * @name 安装添加系统管理员
     * @param $data
     * @author wx
     * @date 2019/11/28 15:30
     */
    function adduser($data)
    {
        //查询授权数量
        $authJson = file_get_contents('./Install/auth.json');
        $authArr = json_decode($authJson, true);

        foreach ($authArr as $k => $v){
            $stime = $v['stime'];
        }

        //1. 添加系统管理员 id只能为1
        $passwordServer = new Password();

        $data['id'] = 1;
        $data['real_name'] = $data['real_name'];
        $data['show_name'] = $data['show_name'];
        $data['password'] = $passwordServer->encrypt($data['password']);
        $data['reg_ip'] = $_SERVER['REMOTE_ADDR'];
        $data['ctime'] = time();
        $data['last_login_ip'] = '';
        $data['last_login_time'] = 0;
        $data['user_group_id'] = 1;
        $data['email'] = $data['email'];
        $data['fid'] = 0;
        $data['token'] = '';

        $userServer = new \app\common\service\ServerUser();

        $adminInfo = $userServer->findData(['id' => 1]);
        if(empty($adminInfo)){
            $userServer->add($data);
        }else{
            $userServer->modify(['id' => $adminInfo['id']], $data);
        }



        //2. 添加用户组
        $addUserGroup['name'] = '超级管理员组';
        $addUserGroup['company'] = '';
        $addUserGroup['upper_id'] = 0;
        $addUserGroup['level'] = 0;
        $addUserGroup['ctime'] = time();
        $addUserGroup['bind_key'] = md5(microtime(true));

        $userGroup = db('server_user_group')->where('id', 1)->find();
        if(empty($userGroup)){
            db('server_user_group')->insert($addUserGroup);
        }else{
            db('server_user_group')->where('id', 1)->update($addUserGroup);
        }

        $stime = time() > $stime ? time() : $stime;
        return $stime;
    }

    /**
     * @name 逻辑处理
     * @param $ip
     * @param $port
     * @author wx
     * @date 2019/12/16 10:34
     */
    function addProxy($ip, $module)
    {
        //1. 获取授权类型
        $content = file_get_contents('./Install/auth.json');
        $arr = json_decode($content, true);
        //端口
        $portArr = array(
            'client' => 7919,
            'defense' => 7920,
            'proxy' => 7921,
            'wipf' => 7922,
        );

        foreach ($arr as $k => $v){
            $mode = $v['mode'];
        }

        if ($mode == 2) {//1单机版,2高可用版
            if(empty($module)){
                returnErrJson($this->CODE_FAIL, '后端IP必须填写');
            }

            $moduleArr = json_decode($module,true);
        }



        $confServer = new SystemConf();

        //测试数据库连接
        $databaseConf = config('database.');


        //连接数据库测试
        $mysqlIp = '127.0.0.1';
        $link = @mysqli_connect($mysqlIp, $databaseConf['username'], $databaseConf['password'],$databaseConf['database'], $databaseConf['hostport']);

        if (!$link){
            $this->setError($this->CODE_FAIL, '数据库连接失败!');
            return false;
        }

        $insertData = array();

        if($mode == 1){//单机版
            foreach ($portArr as $type => $port){
                $tmp['ip'] = $ip;
                $tmp['type'] = $type;
                $tmp['port'] = $port;
                $tmp['used'] = 0;
                $tmp['ip_type'] = 2;
                $insertData[] = $tmp;
            }
        }else{//高可用版
            foreach ($moduleArr as $k => $v){
                if(!empty($v['backend_ip'])){
                    $ipArr = explode(',',$v['backend_ip']);
                    foreach ($ipArr as $backendIp){
                        $temp['ip'] = $backendIp;
                        $temp['type'] = $v['type'];
                        $temp['port'] = $portArr[$v['type']];
                        $temp['used'] = 0;
                        $temp['ip_type'] = 3;
                        $insertData[] = $temp;
                    }
                }
            }

        }

        $php = array(
            array(
                'ip' => $ip,
                'type' => 'php',
                'port' => '7917',
                'used' => 0,
                'ip_type' => 1,
            ),
            array(
                'ip' => $mysqlIp,
                'type' => 'mysql',
                'port' => '7916',
                'used' => 0,
                'ip_type' => 1,
            )
        );


        $allInstertData = array_merge($php, $insertData);

        //1. 修改PHP端数据库配置文件
        //$dbStr = $confServer->databaseConf($ip, $databaseConf['hostport'], $databaseConf['database'], $databaseConf['username'], $databaseConf['password']);
        //$dbConfFile = dirname($_SERVER['DOCUMENT_ROOT']).'/config/database.php';
        //file_put_contents($dbConfFile, $dbStr);


        //2. 清除原来的配置
        $server = new \app\common\service\ServerProxy();
        $server->clear();

        //3. 添加现有配置
        $server->addAll($allInstertData);

    }




}